package com.mywork.mvpkodeinxml.presenter

import com.mywork.mvpkodeinxml.base.presenter.BasePresenter
import com.mywork.mvpkodeinxml.common.COMMONAPI_GETUSERLIST
import com.mywork.mvpkodeinxml.common.execute
import com.mywork.mvpkodeinxml.model.response.UserListEntity
import com.mywork.mvpkodeinxml.rx.BaseSubscriber
import com.mywork.mvpkodeinxml.net.service.CommonService
import com.mywork.mvpkodeinxml.net.service.DownloadService
import com.mywork.mvpkodeinxml.view.MainView
import com.zchu.rxcache.data.CacheResult
import com.zchu.rxcache.kotlin.rxCache
import com.zchu.rxcache.stategy.CacheStrategy
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.kodein.di.Kodein
import org.kodein.di.generic.instance
import java.io.File

class MainPresenter(kodein: Kodein) : BasePresenter<MainView>(kodein) {

    //Inject
    override val mView: MainView by kodein.instance()

    //Inject
    val commonService: CommonService by kodein.instance()

    val downloadService: DownloadService by kodein.instance()

    fun getUserList() {
        commonService.getUserList()
            .rxCache(COMMONAPI_GETUSERLIST, CacheStrategy.firstRemote())
            .execute(mView, lifecycleOwner, object : BaseSubscriber<CacheResult<UserListEntity>>(mView) {
                override fun onNext(t: CacheResult<UserListEntity>) {
                    mView.onGetUserList(t.data, t.from.toString())
                }
            })
    }

    fun downLoad(userCode: String, userPassword: String, formId: String, path: String) {
        downloadService
            .download(userCode, userPassword, formId, path)
            .rxCache(COMMONAPI_GETUSERLIST, CacheStrategy.firstRemote())
            .execute(mView, lifecycleOwner, object : Observer<CacheResult<File>> {
                override fun onComplete() {

                }

                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t: CacheResult<File>) {
                    mView.onFileDownload(t)
                }

                override fun onError(e: Throwable) {
                    e.printStackTrace()
                }
            })


    }

}